package com.baizhi.service.impl;

import com.baizhi.dao.OrderDao;
import com.baizhi.dao.OrderDetailDao;
import com.baizhi.Order;
import com.baizhi.OrderItem;
import com.baizhi.service.OrderItemService;
import com.baizhi.util.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.Collection;
import java.util.List;

public class OrderItemServiceImpl implements OrderItemService {
    @Override
    public boolean Order(Order order, Collection<OrderItem> collection) {
        SqlSession sqlSession = MyBatisUtils.openSession();
        try {
            OrderDao mapper = sqlSession.getMapper(OrderDao.class);
            OrderDetailDao detailDao = sqlSession.getMapper(OrderDetailDao.class);
            mapper.order(order);
            System.out.println(order.getId());
            for (OrderItem item : collection) {
                   item.setOrderId(order.getId());
                System.out.println(item.getOrderId());
                   detailDao.orderDetails(item);
            }
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
        return true;
    }
    @Override
    public List<Order> selectMyOrders(int uid) {
        SqlSession sqlSession = null;
        List<Order> orders = null;
        try {
            sqlSession = MyBatisUtils.openSession();
            OrderDao orderDao = sqlSession.getMapper(OrderDao.class);
            orders = orderDao.selectMyOrders(uid);
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
            sqlSession.rollback();
        } finally {
            MyBatisUtils.close(sqlSession);
        }
        return orders;
    }

    @Override
    public boolean updateState(int id) {
        SqlSession session = MyBatisUtils.openSession();
        try {
            OrderDao mapper = session.getMapper(OrderDao.class);
            mapper.updateState(id);
            session.commit();
        } catch (Exception e) {
            session.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
        return true;
    }
}
